﻿using BasicModuleOrm.Db_Context;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using BasicModuleOrm.Model;

namespace BasicModuleOrm.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrderSqlSugarController : ControllerBase
    {
        private SqlSugarContext _sqlSugarContext;

        public OrderSqlSugarController(SqlSugarContext sqlSugarContext)
        {
            _sqlSugarContext = sqlSugarContext;
        }

        /// <summary>
        /// 查询所有商品
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<IEnumerable<Order>> GetOrders()
        {
            //1、查询所有的商品
            var Orders = _sqlSugarContext.sqlSugarClient.Queryable<Order>().ToList();

            //2、返回商品
            return Orders;
        }

        /// <summary>
        /// 查询商品根据商品Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public ActionResult<Order> GetOrder(int id)
        {
            //1、查询所有的商品
            var Order = _sqlSugarContext.sqlSugarClient.Queryable<Order>().InSingle(id);

            //2、返回商品
            return Order;
        }

        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="Order"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<Order> PostOrder(Order Order)
        {
            // 1、添加商品
            _sqlSugarContext.sqlSugarClient.Insertable(Order).ExecuteCommand();

            // 3、返回商品
            return CreatedAtAction(nameof(PostOrder), new { id = Order.Id }, Order);
        }

        /// <summary>
        /// 更新商品通过Id
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Order"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public IActionResult PutOrder(int id, Order Order)
        {
            // 1、查询商品
            var p = _sqlSugarContext.sqlSugarClient.Queryable<Order>().InSingle(id);

            // 2、更新商品
            _sqlSugarContext.sqlSugarClient.Updateable(Order).ExecuteCommand();

            return Ok("更新成功");
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public IActionResult DeleteOrder(int id)
        {
            // 1、查询商品
            var p = _sqlSugarContext.sqlSugarClient.Queryable<Order>().InSingle(id);

            // 2、更新商品
            _sqlSugarContext.sqlSugarClient.Deleteable<Order>(id).ExecuteCommand();
            return Ok("删除成功");
        }
    }
}
